package com.chenxinzhimusic.viewmodel

import android.content.Context
import androidx.compose.animation.core.Animatable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.media3.common.MediaItem
import com.chenxinzhimusic.service.MusicService.Companion.controller
import kotlinx.coroutines.launch

class MusicViewModel(app: Context) : ViewModel() {
    var nowPlayCurrent: MediaItem? by mutableStateOf(null)
    var isPlaying by mutableStateOf(false)
    var position by mutableIntStateOf(0)
    var duration by mutableIntStateOf(1)
    var durationM by mutableIntStateOf(0)
    var cover by mutableStateOf("")
    val rotation = Animatable(0f)
    var musicId: String? by mutableStateOf(null)
    var lycList by mutableStateOf(
        "[00:00.00] 暂无歌词"
            .split("\n").associate {

                (if (it.length > 8) {
                    it.substring(1, 9)
                } else {
                    it
                }) to if (it.length > 8) {
                    it.substring(10)
                } else {
                    ""
                }
            }
            .filter {
                it.key.isNotBlank()
            }
            .map {
                convertToSeconds(it.key) to it.value
            }.toList()
    )
    var lycIndex by mutableIntStateOf(0)

    fun convertToSeconds(time: String): Double {
        val parts = time.split(":")
        val minutes = parts[0].toInt()
        val secondsAndMillis = parts[1].split(".")
        val seconds = secondsAndMillis[0].toInt()
        val millis = secondsAndMillis[1].toInt()

        // 将分钟转换为秒，并加上秒和毫秒（毫秒转换为秒）
        return minutes * 60 + seconds + millis / 1000.0
    }


    init {

        viewModelScope.launch {
            nowPlayCurrent = controller?.currentMediaItem
        }
    }


}
